Public Module Swizzle
    Public Enum SwizzleType As Byte
        Swizzle = &H0
        DeSwizzle = &H1
    End Enum
    Public Function Swizzle(ByVal bin() As Byte, ByVal width As Integer, ByVal height As Integer, _
    ByVal depth As Integer, ByVal BitCount As Integer, ByVal Action As SwizzleType) As Byte()
        Dim swiz As New SwizzleClass(width, height, depth)
        Dim tmp1, tmp2 As Integer
        Dim bChunk() As Byte

        ReDim bChunk(bin.Length - 1)
        For y As Integer = 0 To height - 1
            For x As Integer = 0 To width - 1
                Select Case Action
                    Case SwizzleType.DeSwizzle
                        tmp1 = ((y * width) + x) * (BitCount / 8)
                        tmp2 = (swiz.Swizzle(x, y, -1)) * (BitCount / 8)
                    Case SwizzleType.Swizzle
                        tmp2 = ((y * width) + x) * (BitCount / 8)
                        tmp1 = (swiz.Swizzle(x, y, -1)) * (BitCount / 8)
                End Select
                For i As Integer = 0 To (BitCount / 8) - 1
                    bChunk(tmp1 + i) = bin(tmp2 + i)
                Next
            Next
        Next
        Return bChunk
    End Function
End Module
Public Class SwizzleClass
    Public m_MaskX As Integer = 0
    Public m_MaskY As Integer = 0
    Public m_MaskZ As Integer = 0
    Public Sub New(ByVal width As Integer, ByVal height As Integer, ByVal depth As Integer)
        Dim bit As Integer = 1
        Dim idx As Integer = 1

        While (bit < width) Or (bit < height) Or (bit < depth)

            If (bit < width) Then
                m_MaskX = m_MaskX Or idx
                idx <<= 1
            End If

            If (bit < height) Then
                m_MaskY = m_MaskY Or idx
                idx <<= 1
            End If

            If (bit < depth) Then
                m_MaskZ = m_MaskZ Or idx
                idx <<= 1
            End If

            bit <<= 1
        End While
    End Sub
    Public Function Swizzle(ByVal Sx As Integer, ByVal Sy As Integer, Optional ByVal Sz As Integer = -1) As Int64
        Swizzle = SwizzleAxis(Sx, m_MaskX) Or SwizzleAxis(Sy, m_MaskY) Or (IIf(Sz <> -1, SwizzleAxis(Sz, m_MaskZ), 0))
    End Function
    Public Function SwizzleAxis(ByVal Value As Integer, ByVal Mask As Integer) As Int64
        Dim Result As Int64
        Dim bit As Integer = 1

        While bit <= Mask
            If (Mask And bit) Then
                Result = Result Or (Value And bit)
            Else
                Value <<= 1
            End If
            bit <<= 1
        End While
        SwizzleAxis = Result
    End Function
End Class